/// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections.ObjectModel;
using System.Xml;
using System.Diagnostics;
using System.IO;

namespace Microsoft.VSPowerToys.Common.TaskManager.ContentInstaller
{
    /// <summary>
    /// Represents a vscontent file. This class is used to read content information.
    /// </summary>
    public class VsiPackage
    {

        private List<BaseVSContent> contentCollection = new List<BaseVSContent>();

        public ReadOnlyCollection<BaseVSContent> Contents
        {
            get { return new ReadOnlyCollection<BaseVSContent>(contentCollection); }
        }
 
        /// <summary>
        /// Reads contents of a vscontent file in to this object
        /// </summary>
        /// <param name="filename">Full path to the content file</param>
        /// <returns>true if successful</returns>
        public bool ReadVSContentFile(string fileName)
        {
            XmlDocument document = new XmlDocument();
            document.Load(fileName);
            XmlNodeList rootNodes = document.GetElementsByTagName("VSContent");
            if (rootNodes.Count == 1)
            {
                XmlNode rootNode = rootNodes[0];
                // Verify xmlns attribute
                if (rootNode.Attributes == null || rootNode.Attributes["xmlns"] == null &&
                    !rootNode.Attributes["xmlns"].Equals("http://schemas.microsoft.com/developer/vscontent/2005"))
                {
                    Debug.WriteLine("xmlns attribute not found or invalid");
                    return false;
                }
                foreach (XmlNode contentNode in rootNode.ChildNodes)
                {
                    if (!contentNode.Name.Equals("Content"))
                    {
                        Debug.WriteLine("Unknown node encountered in VSContent node");
                        return false;
                    }
                    BaseVSContent vsContent = BaseVSContent.CreateFromXmlNode(contentNode);
                    if (vsContent != null)
                    {
                        vsContent.BasePath = Path.GetFullPath(Path.GetDirectoryName(fileName));
                        this.contentCollection.Add(vsContent);
                    }
                }
                return true;
            }
            else
            {
                Debug.WriteLine("VSContent node couldn't be found or invalid");
                return false;
            }
        }
    }
}
